package comm;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Observable;

public class UdpReceiver extends Observable implements Runnable{

	private MulticastSocket socket;
	private InetAddress group;
	private NetworkInterface ni;

	public UdpReceiver (NetworkInterface ni, int port, String groupName) throws IOException{

		//setting up socket
		this.ni = ni;
		socket =  new MulticastSocket(port);
		group = InetAddress.getByName(groupName);

	}

	@Override
	public void run() {
		//try to receive a packet on the network interface

		try{
			socket.setNetworkInterface(ni);
			socket.joinGroup(group);
			DatagramPacket packet;

			byte[] buf = new byte[ni.getMTU()];
			packet = new DatagramPacket(buf, buf.length);

			while (!socket.isClosed()){
				socket.receive(packet); //waiting to receive packet

				//System.out.println("Group: " +group.getHostAddress() +" in Receiver received packet");
				//setChanged and notify any observers with the packet data
				this.setChanged();
				this.notifyObservers(packet);
			}
		}
		catch(SocketException e){
			System.out.println("Socket Exception on interface: "+ni.getDisplayName() +" in the Receiver");
			System.out.println("Group: "+group.getHostAddress());
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		close();

	}

	public void close(){
		socket.close();
	}

}
